<?php
namespace Admin\Controller;

use Common\Model\RefundModel;
use Think\Controller;
use Think\Model;


class RefundController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $this->local_id = session('userInfo')['local_id'];
        if (!$this->local_id) $this->local_id = 1;
    }

    /**
     * 退款退货
     */
    public function index()
    {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $view = I('param.view', 1);
        $this->assign('p', $p);
        $this->assign('num', $num);
        $this->assign('view', $view);

        $order_field = I('param.order_field', 'id');
        $order = I('param.order', 'desc');
        $this->assign('order_field', $order_field);
        $this->assign('order', $order);
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);

        $order = array($order_field => $order);

        $search_field = I('param.search_field', 'name');
        $search = I('param.search');
        $where[] = ' 1=1 ';
        $where[] = array('b.local_id' => $this->local_id);
        $where[] = array('a.status' => $view);
        if ($view == 9) {
            array_pop($where);
            $where[] = array('a.status' =>['neq', '7']);
        } elseif($view == 8) {
            array_pop($where);
            $where[] = "(a.status='4' and a.type='3') or (a.status='2' and a.type !='3')";
        }

        /************** 冉 3-9 确认收货***********************/
        if ($view == 3) {
            array_pop($where);
            $where[] = array('a.status' =>['in', ['3','2']],'type' =>'3');
        }

        /*************************************/
        if ($search && $search_field) {
            $this->assign('search_field', $search_field);
            $this->assign('search', $search);
            if ($search_field == 'order_id') {
                $search_field = 'a.'.$search_field;
            } else {
                $search_field = 'b.'.$search_field;
            }
            $where[] = $search_field . " like '%" . $search . "%'";
        }

        $count = M('b2c_refund_money')
            ->alias('a')
            ->join(C('DB_PREFIX') . 'b2c_orders b on a.order_id=b.order_id')
            ->where($where)
            ->count();
        if ($count > 0) {
            $Page = new \Think\Page($count, $num);
            $show = $Page->show();

            $list = M('b2c_refund_money')
                ->alias('a')
                ->join(C('DB_PREFIX') . 'b2c_orders b on a.order_id=b.order_id')
                ->field('a.*,b.createtime,b.ship_name,b.ship_mobile')
                ->where($where)
                ->order($order)
                ->page($p, $num)
                ->select();

            foreach ($list as &$item) {
                if($item['store_work_logs']) {
                    $tmp = json_decode($item['store_work_logs'], true);
                    $price = array_pop($tmp);
                    $item['store_money'] = $price['store_money'];
                }
                $item['state'] = $this->_getStatus($item['status']);

            }
            $this->assign('list', $list);
            $this->assign('page', $show);
        }
        $this->display();
    }

    protected function _getStatus($status) {
        switch ($status) {
            case '0':
                $status_desc = '已取消';
                break;
            case '1':
                $status_desc = '待初审核中';
                break;
            case '2':
                $status_desc = '初审成功';
                break;
            case '3':
                $status_desc = '用户已发退货';
                break;
            case '4':
                $status_desc = '确认收到退货';
                break;
            case '5':
                $status_desc = '退货退款完成';
                break;
            case '6':
                $status_desc = '重新申请';
                break;
            case '7':
                $status_desc = '用户取消申请';
                break;
        }
        return $status_desc;
    }

    /**
     * 获取退单的详细信息
     * 订单详情
     * 退单详情
     * 退货商品信息
     * return json
     */
    public function getOrderDetail($id,$order_id)
    {
        $id = I('get.id') ? I('get.id') : $id;
        $order_id = I('get.order_id') ? I('get.order_id') : $order_id;
        if (!$id) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $refund_model = new RefundModel();
        $res = $refund_model->getOrderDetail($id,$order_id);
        $this->assign($res);
        if (!IS_AJAX) return;
        $html = $this->fetch('Admin@Refund:refundInfo');
        $return = array(
            'status' => true,
            'message' => '获取成功',
            'data' => $html
        );
        $this->ajaxReturn($return);
    }


    /**
     * 初审状态修改
     * 初审成功 / 失败
     */
    public function changeDeliveryFirst()
    {
        if (!IS_AJAX) {
            $this->error('错误的请求方式');
        }
        $id = I('post.id');
        $status = I('post.status'); //1-审核成功 2-失败
        $desc = I('post.desc');
        $current_price = I('post.price');
        $bonus = I('post.bonus');
        $price = $current_price + $bonus; // 总金额 = 确认退款金额 + 确认返还奖金金额
        $wuliu_name = I('post.wuliu_name');
        $wuliu_no = I('post.wuliu_no');
        $time = time();
        $behavior = '';
        //`status` enum('5','4','3','2','0','6','1') NOT NULL DEFAULT '1' COMMENT '退款状态，1用户申请，2审核通过，3用户退货, 4确认退货, 5退货、退款完成,6重新申请',
        //`type` enum('2','1') NOT NULL DEFAULT '1' COMMENT '1退款，2退款退货',
        $info = M('b2c_refund_money')->where(['id'=>$id])->find();
        //`pay_status` enum('0','1') NOT NULL DEFAULT '0' COMMENT '付款状态：0-未付款、1-已支付',
        //`ship_status` enum('0','1') NOT NULL DEFAULT '0' COMMENT '发货状态：0-未发货、1-已发货',
        //refund_ago_goods_status 售后退款退货，初始0，申请中1，完成2
        //refund_ago_money_status 售后退款，初始0，申请中1，完成2
        //refund_front_status 售前退款，初始0，申请中1，完成2
        $order = M('b2c_orders')->where(['order_id'=>$info['order_id']])->field(['pay_status','ship_status','refund_ago_goods_status','refund_ago_money_status','refund_front_status', 'order_msg'])->find();

        if ($status == '0') {
            //店铺管理员拒绝

            $db = new Model();
            $db->startTrans();

            $save = $this->updateAdminLog($id, '0', $info, $price, $time, $desc, $bonus);
            $save2 = $this->updateOrderLog($info, $time);
            $order_msg = $this->updateOrders($info, '初审不通过');
            /**冉 3-8 初审失败 返回订单状态***/
            $save3 = M('b2c_orders')->where(['order_id'=>$info['order_id']])->save(['refund_front_status'=>'0']);
            /*****************************/

            if ($save !== false && $save2 !== false && $order_msg !==false && $save3 !== false) {
                $db->commit();
                $return = ['status' => true, 'message' => '操作成功,初审不通过', 'data' => ''];
            } else {
                $db->rollback();
                $return = ['status' => false, 'message' => '操作失败,重新来过', 'data' => ''];
            }

        } elseif($status == '1') {
            //店铺管理员初审通过
            $res = false;
            if ($info['type'] == '1' ) {
                //售前退款
                if ($order['pay_status'] == '1' &&  $order['ship_status'] == '0' && $order['refund_front_status'] == '1') {
                    $res = true;
                }
                $msg = '初审 售前退款成功';
                $behavior = 'member_refund';
            } elseif($info['type'] == '2' ) {
                //售后退款
                if ($order['pay_status'] == '1' && $order['ship_status'] == '1' && $order['refund_ago_money_status'] == '1') {
                    $res = true;
                }
                $msg = '初审 售后退款成功';
                $behavior = 'member_refund_goods';
            } elseif($info['type'] == '3') {
                //售后退货退款
                if ($order['pay_status'] == '1' && $order['ship_status'] == '1' && $order['refund_ago_goods_status'] == '1') {
                    $res = true;
                }
                $msg = '初审 售后退货退款成功';
                $behavior = 'member_refund_goods';
            }
            if (!$res) {
                $return = ['status' => false, 'message' => '请先确认 初审退款（退货退款）是否成功', 'data' => ''];
                $this->ajaxReturn($return);
            }

            $db = new Model();
            $db->startTrans();
            $save = $this->updateAdminLog($id, '2', $info, $price, $time, $desc, $bonus);

            $add_log = [
                'rel_id' => $info['order_id'],
                'op_id' => session('userInfo')['id'],
                'op_name' => session('userInfo')['username'],
                'alttime' => $time,
                'behavior' => $behavior,
                'result' => 'SUCCESS',
                'log_text' => $msg,
            ];
            $add_res = M('b2c_order_log')->add($add_log);

            $order_msg = $this->updateOrders($info, $msg);

            if ($save !== false && $order_msg !== false && $add_res !== false) {
                $db->commit();
                $return = ['status' => true, 'message' => '操作成功,初审通过', 'data' => ''];
            } else {
                $db->rollback();
                $return = ['status' => false, 'message' => '操作失败,系统错误', 'data' => ''];
            }

        } elseif($status == '4') {
            //店铺管理员确认收货

            $res = false;
            if ($order['pay_status'] == '1' && $order['ship_status'] == '1' && $order['refund_ago_goods_status'] == '1') {

                $res = true;
                if(empty($wuliu_name)&&empty($wuliu_no)){
                    $msg = '已收到退货,等待财务审核中';
                }else{
                    $msg = '已收到退货,等待财务审核中'.'物流公司：'.$info['wuliu_name'].'物流单号：'.$info['wuliu_no'];
                }

                $behavior = 'refunds';
            }
            if (!$res) {
                $return = ['status' => false, 'message' => '请等待店铺管理员确认收到退货', 'data' => ''];
                $this->ajaxReturn($return);
            }


            /**入库物流信息 冉 3-10**/
            $info['json_msg'] = json_decode($info['json_msg'], true);
            $info['json_msg']['d'] = ['time' => $time];
            $info['json_msg'] = json_encode($info['json_msg']);

            $data1 = [
                'wuliu_no' => $wuliu_no,
                'wuliu_name' => $wuliu_name,
                'json_msg' => $info['json_msg'] // json数据
            ];

            $iswuliu = M('b2c_refund_money')->where(['order_id' => $info['order_id'], 'id' => $info['id']])->save($data1);

            /****************************************/
            $db = new Model();
            $db->startTrans();
            $save = $this->updateAdminLog($id, '4', $info, $price, $time, $desc, $bonus);
            $order_msg = $this->updateOrders($info, $msg);



            $add_log_4 = [
                'rel_id' => $info['order_id'],
                'op_id' => session('userInfo')['id'],
                'op_name' => session('userInfo')['username'],
                'alttime' => $time,
                'behavior' => $behavior,
                'result' => 'SUCCESS',
                'log_text' => $msg,
            ];
            $add_res = M('b2c_order_log')->add($add_log_4);


            if ($save !== false && $order_msg !== false && $add_res !== false && $iswuliu !== false) {
                $db->commit();
                $return = ['status' => true, 'message' => '操作成功,确认收到货物,该退单已提交给平台进行审核', 'data' => ''];
            } else {
                $db->rollback();
                $return = ['status' => false, 'message' => '操作失败,系统错误', 'data' => ''];
            }
        }
        $this->ajaxReturn($return);
    }

    //b2c_refund_money
    protected function updateAdminLog($id, $status, $info, $price, $time, $desc, $bonus) {
        //管理员日志
        if ($status == '0') {
            $key = 'a';
            $price = '0';
        } elseif($status == '2') {
            $key = 'c';
        } elseif($status == '4') {
            $key = 'e';
        }
        if ($info['store_work_logs']) {
            $arr = json_decode($info['store_work_logs'], true);
            $log = [
                'store_money'=> $price,
                'store_confirm_t'=>$time,
                'store_memo'=>$desc,
                'store_user'=>session('userInfo')['username'],
                'store_user_id'=>session('userInfo')['id'],
                'bonus_money'=> $bonus,
            ];
            array_push($arr, $log);
        } else {
            $arr[0] = [
                'store_money'=> $price,
                'store_confirm_t'=>$time,
                'store_memo'=>$desc,
                'store_user'=>session('userInfo')['username'],
                'store_user_id'=>session('userInfo')['id'],
                'bonus_money'=> $bonus,
            ];
        }
        //操作时间流程
        $json_msg = [];
        if ($info['json_msg']) {
            $json_msg = json_decode($info['json_msg'], true);

            $json_msg[$key] = ['time' => $time];
        } else {
            $json_msg[$key] = ['time' => $time];
        }
        $save = [
            'status' => $status,
            'store_work_logs'=>json_encode($arr),
            'json_msg' => json_encode($json_msg)
        ];
        //保存到b2c_refund_money
        $save = M('b2c_refund_money')->where(['id'=>$id])->save($save);
        return $save;
    }

    //b2c_order_log
    protected function updateOrderLog($info, $time) {
        $add = [
            'rel_id' => $info['order_id'],
            'op_id' => session('userInfo')['id'],
            'op_name' => session('userInfo')['username'],
            'alttime' => $time,
            'behavior' => 'refund_fail',
            'result' => 'SUCCESS',
            'log_text' => '初审失败',
        ];
        $add = M('b2c_order_log')->add($add);
        return $add;
    }

    //b2c_orders
    protected function updateOrders($info, $msg) {
        $save = M('b2c_orders')->where(['order_id'=>$info['order_id']])->save(['order_msg'=>$msg]);
        return $save;
    }
}